<script setup>
import {Lock, Phone, User, View} from '@element-plus/icons-vue'
import {onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {userLoginService, userRegisterService} from '@/api/teacher.js'
import {useTokenStore} from '@/stores/token.js'
import {useRouter} from 'vue-router'

let isRegister = ref(false)
const registerData = ref({
  id: '',
  name: '',
  password: '',
  rePassword: '',
  phoneNumber: '',
})


const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

const rules = {
  name: [
    {required: true, message: '请输入名字', trigger: 'blur'},
    {min: 1, max: 8, message: '长度为1~8位非空字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
  ],
  phoneNumber: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: 'blur'}
  ]
}

const router = useRouter()
const tokenStore = useTokenStore();

const register = async () => {

  if (!registerData.value.name || !registerData.value.password || !registerData.value.rePassword) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (registerData.value.password !== registerData.value.rePassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  await userRegisterService(registerData.value);
  ElMessage.success('注册成功')
  verificationCodeText.value = "";
  clearRegisterData();
  isRegister = false

}

const login = async () => {
  if (verificationCodeText.value.toLowerCase !== verificationCode.value.toLowerCase) {
    ElMessage.error('验证码错误');
    draw();
    verificationCodeText.value = "";
  } else {
    let result = await userLoginService(registerData.value);
    ElMessage.success('登录成功')
    verificationCodeText.value = "";
    tokenStore.setToken(result.data)
    await router.push('/StudentSystem/')
  }
}

const clearRegisterData = () => {
  registerData.value = {
    id: '',
    name: '',
    password: '',
    rePassword: '',
    email: ''
  }
}

let verificationCode = ref("");
let verificationCodeText = ref("");
const show_num = [];
onMounted(() => {
  draw();
});

const draw = () => {
  var canvas_width = document.getElementById("canvas").clientWidth;
  var canvas_height = document.getElementById("canvas").clientHeight;
  var canvas = document.getElementById("canvas"); //获取到canvas的对象，画布
  var context = canvas.getContext("2d"); //画笔

  canvas.width = canvas_width;
  canvas.height = canvas_height;

  var sCode =
      "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
  var aCode = sCode.split(",");
  var aLength = aCode.length;
  for (var i = 0; i <= 3; i++) {
    var j = Math.floor(Math.random() * aLength);
    var deg = (Math.random() * 30 * Math.PI) / 180;
    var txt = aCode[j];
    show_num[i] = txt;
    var x = 10 + i * 20;
    var y = 20 + Math.random() * 8;
    context.font = "23px 微软雅黑";
    context.translate(x, y);
    context.rotate(deg);
    context.fillStyle = randomColor();
    context.fillText(txt, 0, 0);
    context.rotate(-deg);
    context.translate(-x, -y);
  }
  for (var i = 0; i <= 5; i++) {
    context.strokeStyle = randomColor();
    context.beginPath();
    context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
    context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
    context.closePath();
    context.stroke();
  }
  for (var i = 0; i <= 30; i++) {
    context.strokeStyle = randomColor();
    context.beginPath();
    var x = Math.random() * canvas_width;
    var y = Math.random() * canvas_height;
    context.arc(x, y, 1, 0, 2 * Math.PI);
    context.closePath();
    context.stroke();
  }

  function randomColor() {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return `rgb(${r},${g},${b})`;
  }

  verificationCode.value = show_num.join("");
  return show_num;
}
</script>

<template>
  <div class="main"> 
  <el-row class="left"></el-row>
  <el-row class="right">
    <el-col :offset="3" :span="6" class="form">
      <!-- 注册表单 -->
      <el-form v-if="isRegister" ref="form" :model="registerData" :rules="rules" autocomplete="off" size="large">
        <el-form-item>
          <h1 class="title">注册</h1>
        </el-form-item>
        <el-form-item prop="name">
          <el-input v-model="registerData.name" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input v-model="registerData.phoneNumber" :prefix-icon="Phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerData.password" :prefix-icon="Lock" placeholder="请输入密码"
                    type="password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input v-model="registerData.rePassword" :prefix-icon="Lock" placeholder="请再次输入密码"
                    type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button auto-insert-space class="button" type="primary" @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link :underline="false" style="color: #000000;" type="info"
                   @click="isRegister = false; clearRegisterData();">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form v-else ref="form" :model="registerData" :rules="rules" autocomplete="off" size="large">
        <el-form-item>
          <h1 class="title">欢迎来到高校学生信息管理系统</h1>
        </el-form-item>
        <el-form-item prop="phoneNumber">
          <el-input v-model="registerData.phoneNumber" :prefix-icon="User" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="registerData.password" :prefix-icon="Lock" name="password" placeholder="请输入密码"
                    type="password"></el-input>
        </el-form-item>
        <el-form-item id="verificationCode">
          <el-input v-model="verificationCodeText" :prefix-icon="View" class="verificationCodeInput" name="verification"
                    placeholder="请输入验证码" type="text"></el-input>
          <div>
            <canvas id="canvas" class="canvas" @click="draw"></canvas>
          </div>
        </el-form-item>

        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox style="color: #000000;">记住我</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button auto-insert-space class="button" type="primary" @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link :underline="false" style="color: #000000;" type="info"
                   @click="isRegister = true; clearRegisterData();">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</div>  
</template>

<style lang="scss" scoped>
.left{
  height: 100vh;
  background: url('@/assets/LoginBg.png') no-repeat;
  border-radius: 0 20px 20px 0;
  width: 60%;
  background-size: cover;
  position: relative;
  left: 0;
  top: 0;
  display: inline-block;
}

.right {
  height: 100vh;
  background: #fff;
  border-radius: 0 20px 20px 0;
  width: 40%;
  background-size: cover;
  position: relative;
  right: 0;
  top: 0;
  display: inline-block;

  .form {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    padding: 25px;
    width: 26%;
    min-width: 460px;
    height: 30%;
    min-height: 500px;
    background: rgba(0, 200, 255, 0.3);
    border-radius: 5%;
    box-shadow: 2px 2px 10px #ddd;


    #emailCode {
      display: flex;
      width: 100%;

      .emailCodeInput {
        width: 65%;
      }

      .emailButton {
        width: 130px;
        height: 38px;
        border-radius: 5px;
        margin-left: 5px;
      }
    }

    #verificationCode {
      display: flex;
      width: 100%;

      .container {
        display: flex;
        align-items: center;
      }

      .verificationCodeInput {
        width: 65%;
      }

      .canvas {
        width: 130px;
        height: 38px;
        border-radius: 5px;
        background: white;
        margin-left: 5px;
        margin-top: 15px;
      }
    }


    .title {
      margin: 0 auto;
      text-align: center;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>